Grokking Amazon Coding Interview
Rate this course
Ask Author
Contribute
Back to course home

0% completed

Vote For New Content
Introduction
Who Should Take This Course?
Amazon Easy Problems
Redistribute Characters to Make All Strings Equal (easy)
Solution: Redistribute Characters to Make All Strings Equal
Longest Common Prefix (easy)
Solution: Longest Common Prefix
Make Array Zero by Subtracting Equal Amounts (easy)
Solution: Make Array Zero by Subtracting Equal Amounts
Leaf-Similar Trees (easy)
Solution: Leaf-Similar Trees
Path Crossing (easy)
Solution: Path Crossing
Special Array With X Elements Greater Than or Equal X (easy)
Solution: Special Array With X Elements Greater Than or Equal X
Relative Sort Array (easy)
Solution: Relative Sort Array
Transpose Matrix (easy)
Solution: Transpose Matrix
Find Common Characters (easy)
Solution: Find Common Characters
Fizz Buzz (easy)
Solution: Fizz Buzz
Increasing Order Search Tree (easy)
Solution: Increasing Order Search Tree
Largest Odd Number in String (easy)
Solution: Largest Odd Number in String
Best Time to Buy and Sell (easy)
Solution: Best Time to Buy and Sell Stock
Take Gifts From the Richest Pile(easy)
Solution: Take Gifts From the Richest Pile
Remove Duplicates from Sorted List (easy)
Solution: Remove Duplicates from Sorted List
Amazon Medium Problems
Maximum Length of Subarray With Positive Product (medium)
Solution: Maximum Length of Subarray With Positive Product
Largest Submatrix With Rearrangements (medium)
Solution: Largest Submatrix With Rearrangements
Count the Number of Good Subarrays (medium)
Solution: Count the Number of Good Subarrays
Minimum Suffix Flips (medium)
Solution: Minimum Suffix Flips
Minimum Number of Operations to Make Array Empty (medium)
Solution: Minimum Number of Operations to Make Array Empty
Next Greater Element II (medium)
Solution: Next Greater Element II
Make Sum Divisible by P (medium)
Solution: Make Sum Divisible by P
Rotting Oranges (medium)
Solution: Rotting Oranges
Minimum Deletions to Make Character Frequencies Unique (medium)
Solution: Minimum Deletions to Make Character Frequencies Unique
Minimum Adjacent Swaps to Make a Valid Array (medium)
Solution: Minimum Adjacent Swaps to Make a Valid Array
Reverse Integer (medium)
Solution: Reverse Integer
Maximize Distance to Closest Person (medium)
Solution: Maximize Distance to Closest Person
Split Linked List in Parts (medium)
Solution: Split Linked List in Parts
Maximum Difference Between Node and Ancestor (medium)
Solution: Maximum Difference Between Node and Ancestor
Deepest Leaves Sum (medium)
Solution: Deepest Leaves Sum
The kth Factor of n (medium)
Solution: The kth Factor of n
Coin Change II (medium)
Solution: Coin Change II
Sum of Subarray Minimums (medium)
Solution: Sum of Subarray Minimums
Valid Sudoku (medium)
Solution: Valid Sudoku
Longest Increasing Subsequence (medium)
Solution: Longest Increasing Subsequence
Next Permutation (medium)
Solution: Next Permutation
Subsets (medium)
Solution: Subsets
Combination Sum (medium)
Solution: Combination Sum
Number of Provinces (medium)
Solution: Number of Provinces
Number of Islands (medium)
Solution: Number of Islands
Constrained Subsequence Sum (hard)
Solution: Constrained Subsequence Sum
Number of Valid Subarrays (hard)
Solution: Number of Valid Subarrays
Count Vowels Permutation (hard)
Solution: Count Vowels Permutation
Concatenated Words (hard)
Solution: Concatenated Words
Minimum Replacements to Sort the Array (hard)
Solution: Minimum Replacements to Sort the Array
Count All Valid Pickup and Delivery Options (hard)
Solution: Count All Valid Pickup and Delivery Options
Length of the Longest Valid Substring (hard)
Solution: Length of the Longest Valid Substring
Count Array Pairs Divisible by K (hard)
Solution: Count Array Pairs Divisible by K
Word Ladder (hard)
Solution: Word Ladder
Path with Maximum Sum (hard)
Solution: Path with Maximum Sum
Solution: Sum of Subarray Minimums

Problem Statement

Given an integer array arr, find the sum of the minimum elements of all possible subarrays of arr. Return the answer modulo as it may be very large.

Examples

Example 1:

  • Input: [2, 3, 1]
  • Expected Output: 10
  • Justification: The subarrays are [2], [3], [1], [2, 3], [3, 1], and [2, 3, 1]. Their minimums are 2, 3, 1, 2, 1, and 1 respectively. Summing these minimums yields 10.

Example 2:

  • Input: [4, 5, 2]
  • Expected Output: 19
  • Justification: The subarrays are [4], [5], [2], [4, 5], [5, 2], and [4, 5, 2]. Their minimums are 4, 5, 2, 4, 2, and 2 respectively. Summing these minimums gives us 19.

Example 3:

  • Input: [7, 2, 8, 4]
  • Expected Output: 35
  • Justification: The subarrays are [7], [2], [8], [4], [7, 2], [2, 8], [8, 4], [7, 2, 8], [2, 8, 4], and [7, 2, 8, 4]. Their minimums are 7, 2, 8, 4, 2, 2, 4, 2, 2, and 2 respectively. Summing these minimums totals 35.

Solution

To solve this problem, we utilize a stack to efficiently track the minimum elements in all subarrays. The essence of this approach lies in its ability to maintain a stack of elements of the input array that are in ascending order. This method ensures that for any given element in the array, we can quickly determine the range of subarrays for which it is the minimum element. This approach is effective because it allows us to process each element of the array exactly once, thus ensuring optimal time complexity.

The rationale behind using a stack is that it enables us to keep track of elements in a way that, when we encounter a new element, we can efficiently find the nearest smaller element to its left and its right. This information is crucial for determining the contribution of each element to the final sum. By calculating the distance to the nearest smaller elements on both sides, we can determine how many subarrays each element is the minimum of, thereby allowing us to calculate its total contribution to the sum. This method is preferred for its efficiency and ability to handle the problem's requirements systematically.

Step-by-step Algorithm

  1. Initialization:

    • Declare a stack that will store pairs of elements from the array and their frequency of being the minimum in subarrays.
    • Initialize two variables, result and currentSum, to store the final sum of subarray minimums and the sum of minimums for the current element being processed, respectively.
    • Define a modulo mod (e.g., 1e9 + 7) to handle large sums and prevent integer overflow.
  2. Iterate Over the Array:

    • For each element in the array, perform the following steps:
      • Initialize a variable count to 1. This variable tracks how many times the current element can be the minimum in its potential subarrays.
  3. Processing Elements in Stack:

    • While the stack is not empty and the top element of the stack is greater than or equal to the current element:
      • Pop the top element from the stack. This element is no longer the minimum for any subarray extending beyond the current element.
      • Subtract the contribution of the popped element (its value multiplied by its count) from currentSum.
      • Add the count of the popped element to the count of the current element, as the current element will now be the minimum for those subarrays too.
  4. Update Stack and Current Sum:

    • Push the current element and its count onto the stack. This action signifies that the current element is now being considered as a potential minimum for upcoming subarrays.
    • Update currentSum by adding the product of the current element's value and its count. This update reflects the new subarrays where the current element is the minimum.
    • Update the result by adding currentSum to it. currentSum represents the sum of minimums for subarrays ending at the current element.
  5. Finalizing the Result:

    • After processing all elements in the array, the result variable will hold the sum of the minimums of all subarrays. Since we are using a modulo operation, ensure the final result is non-negative by adjusting with the modulo if necessary.
  6. Return the Result:

    • Return the result as the final answer to the problem.

Algorithm Walkthrough

Let's take the input [7, 2, 8, 4]:

  1. Initialize an empty stack and variables result and currentSum to 0.

    • Stack: []
    • result: 0
    • currentSum: 0
  2. Iterate through the input array [7, 2, 8, 4]:

    a. For the first element 7:

    • Push [7, 1] onto the stack.
    • Update currentSum to (0 + 7*1) % mod = 7.
    • Update result to (0 + 7) % mod = 7.
    • Stack: [[7, 1]]
    • result: 7
    • currentSum: 7

    b. For the second element 2:

    • Pop [7, 1] from the stack since 2 < 7.
    • Increment count by 1 (from 1 to 2).
    • Update currentSum by subtracting (7 * 1) from it.
    • Push [2, 2] onto the stack.
    • Update currentSum to (7 - 7*1 + 2*2) % mod = 4.
    • Update result to (7 + 4) % mod = 11.
    • Stack: [[2, 2]]
    • result: 11
    • currentSum: 4

    c. For the third element 8:

    • Push [8, 1] onto the stack.
    • Update currentSum to (4 + 8*1) % mod = 12.
    • Update result to (11 + 12) % mod = 23.
    • Stack: [[2, 2], [8, 1]]
    • result: 23
    • currentSum: 14

    d. For the fourth element 4:

    • Pop [8, 1] from the stack since 4 < 8.
    • Increment count by 1 (from 1 to 2).
    • Update currentSum by subtracting (8 * 1) from it.
    • Push [4, 4] onto the stack.
    • Update currentSum to (12 - 8*1 + 4*2) % mod = 12.
    • Update result to (23 + 12) % mod = 35.
    • Stack: [[4, 4]]
    • result: 35
  3. Return the final result, which is 35.

Code

Java
Saved to Cloud

. . . .

Complexity Analysis

Time Complexity

The time complexity of the algorithm , where N is the length of the input array. This efficiency is achieved by traversing the array only once with the help of a stack to track the indices of elements.

For each element, operations within the loop (pushing to or popping from the stack) occur in constant time on average, since each element is pushed onto and popped from the stack exactly once.

Space Complexity

The space complexity is due to the utilization of a stack that, in the worst case, might contain all N elements of the array if the array is sorted in ascending order. This stack is used to keep track of the elements' indices and their count of occurrences as minimums for the subarrays.

Sum of Subarray Minimums (medium)
Valid Sudoku (medium)
Mark as Completed

On this page

Problem Statement

Examples

Solution

Step-by-step Algorithm

Algorithm Walkthrough

Code

Complexity Analysis

Time Complexity

Space Complexity